package 力扣.树.中序遍历;

public class 二叉搜索树节点的最小距离783 {
    public int minDiffInBST(TreeNode root) {
         if (root == null){
             return 0;
         }
         midDfs(root);
         return ans;
    }
    private int preValue = Integer.MIN_VALUE;
    private int ans = Integer.MAX_VALUE;
    private void midDfs(TreeNode root){
        if (root != null){
            midDfs(root.left);
            if (preValue != Integer.MIN_VALUE){
                int te = root.val - preValue;
                ans = Math.min(te, ans);
            }
            preValue = root.val;
            midDfs(root.right);
        }
    }



    public int minDiffInBST2(TreeNode root) {
       midDfs2(root);
       return ans2;
    }
    private int pre2 = Integer.MIN_VALUE;
    private int ans2 = Integer.MAX_VALUE;
    private void midDfs2(TreeNode root){
        if (root != null){
            midDfs2(root.left);
            int te = root.val;
            if (pre2 != Integer.MIN_VALUE){
                int p = te - pre2;
                if (p < ans2){
                    ans2 = te - pre2;
                }
            }
            pre2 = te;
            midDfs2(root.right);
        }
    }
}
